Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Jump Statements

Return in Java

Return Statement

In Java, the return statement is a fundamental control statement that serves various purposes within methods. It allows you to terminate the execution of a method and return a value (if the method has a return type) to the calling code. The return statement plays a crucial role in managing the flow of a Java program, and its usage varies depending on the context. Here's a detailed explanation of the return statement in Java:

Terminating a Method:

The primary purpose of the return statement is to exit a method prematurely. When a return statement is encountered within a method, it immediately terminates the method's execution, and control is passed back to the calling code.
integer return Example in java
public class Main{ public static void main(String args[]) { HelloWorld obj=new HelloWorld(); int result=obj.add(23,33); System.out.println(result); } } public class HelloWorld { public int add(int a, int b) { int sum = a + b; return sum; // Terminate the method and return the 'sum' value } }

Output

56
In this example, the add method takes two integers as input, calculates their sum, and returns it using the return statement.

Returning a Value:

The return statement is used to send a value back to the calling code. If a method has a return type (e.g., int, double, String, etc.), it must use a return statement to provide a value of that type.
Square root calculation - return int example
public class Main{ public static void main(String args[]) { Squareroot obj=new Squareroot(); int result=obj.calculateSquare(112); System.out.println(result); } } public class Squareroot { public int calculateSquare(int x) { return x * x; // Calculate the square and return it } }

Output

12544
Here, the calculateSquare method computes the square of an integer x and returns the result.

Multiple Return Statements:

Methods can have multiple return statements, but only one of them is executed. The specific return statement that is executed depends on the flow of the program. This allows you to have conditional returns based on different situations.
greater in two numbers
public class Main{ public static void main(String args[]) { FindMaximum obj=new FindMaximum(); int result=obj.max(112,344); System.out.println(result); } } public class FindMaximum { public int max(int a, int b) { if (a > b) { return a; // Return 'a' if it's greater } else { return b; // Return 'b' if it's greater or equal } } }

Output

344
In this example, the max method returns the maximum of two integers by using conditional return statements.

Void Methods:

If a method has a return type of void, it can still use the return statement, but without returning a value. In this case, the return statement is used to exit the method early.
Void Returning example in java
public class Main{ public static void main(String args[]) { VoidReturn obj=new VoidReturn(); obj.printMessage("Hello"); } } public class VoidReturn { public void printMessage(String message) { if (message == null) { return; // Exit the method if 'message' is null } System.out.println(message); } }

Output

Hello
Here, the printMessage method checks if the input message is null and, if so, exits the method without printing anything.

Exception Handling:

In methods that handle exceptions, the return statement is often used to exit the method in exceptional situations. For example, if an error occurs, you can use return to indicate that an exceptional condition has been encountered.
ExeptionHandling return example
public class Main{ public static void main(String args[]) { ExeptionHandling obj=new ExeptionHandling(); int result=obj.divide(123,10); System.out.println(result); } } public class ExeptionHandling { public int divide(int dividend, int divisor) { if (divisor == 0) { throw new IllegalArgumentException("Division by zero is not allowed."); } return dividend / divisor; } }

Output

12
In this case, if the divisor is zero, the method throws an exception, and the return statement is never reached.

Returning an Array:

In methods, when working with an array which has sequential set of values return like the below example.
Return array example in Java
public class Main{ public static void main(String args[]) { ArrayReturn obj=new ArrayReturn(); int[] result=obj.createArray(12); int i; for(i=0;i < result.length;i++){ System.out.println(result[i]); } } } public class ArrayReturn{ public int[] createArray(int size) { int[] newArray = new int[size]; for (int i = 0; i < size; i++) { newArray[i] = i * 2; // Populate the array with even numbers } return newArray; } }

Output

0 2 4 6 8 10 12 14 16 18 20 22
In this example, the createArray method creates an integer array, populates it with even numbers, and returns the array.

Returning a String:

Below code is an example of string method and it has return statement to return the string.
String return example in java
public class Main{ public static void main(String args[]) { StringReturn obj=new StringReturn(); String result=obj.greet("Tutorialsbox"); System.out.println(result); } } public class StringReturn{ public String greet(String name) { if (name == null || name.isEmpty()) { return "Hello, Guest!"; } else { return "Hello, " + name + "!"; } } }

Output

Hello, Tutorialsbox!
The greet method takes a name as input and returns a greeting message. If the name is null or empty, it returns a generic greeting to a guest.

Returning a Boolean in java

Below code is an example of boolean method and it has return statement to return the boolean value like true or false.
Return boolean
public class Main{ public static void main(String args[]) { BooleanReturn obj=new BooleanReturn(); boolean result=obj.isEven(112); System.out.println(result); } } public class BooleanReturn{ public boolean isEven(int number) { return number % 2 == 0; } }

Output

true
In this example, the isEven method checks if a given number is even and returns true if it is, or false if it's not.

Returning a Character in java

Below code is an example of char method and it has return statement to return the char value based on the index. Here the index is 0.
Return a character
public class Main{ public static void main(String args[]) { CharacterReturn obj=new CharacterReturn(); char result=obj.getFirstCharacter("TutorialsBox"); System.out.println(result); } } public class CharacterReturn{ public char getFirstCharacter(String input) { if (input == null || input.isEmpty()) { return '\0'; // Return null character for empty or null input } else { return input.charAt(0); // Return the first character of the input string } } }

Output

T
Here, the getFirstCharacter method returns the first character of a given string, or the null character ('\0') if the input is empty or null.

Returning a Double in java

Below code is an example of double method and it has return statement to return the double.
Double return
public class Main{ public static void main(String args[]) { ReturnDouble obj=new ReturnDouble(); double result=obj.calculateArea(1.1234); System.out.println(result); } } public class ReturnDouble{ public double calculateArea(double radius) { return Math.PI * radius * radius; // Calculate and return the area of a circle } }

Output

3.9647765111238513
This method calculates and returns the area of a circle based on the radius.

Returning an Object in java

Below code is an example of method which has object. person is the object and it has return statement to return the new object.
Returning an Object
public class Main { public static void main(String[] args) { ObjectReturn obj = new ObjectReturn(); Person result = obj.createPerson("Tutorialsbox", 1); System.out.println(result.name); } } class Person { String name; int age; public Person(String name, int age) { this.name = name; this.age = age; } } class ObjectReturn { public Person createPerson(String name, int age) { return new Person(name, age); // Create and return a Person object } }

Output

Tutorialsbox
In this example, the createPerson method creates a Person object with a given name and age and returns the object. These examples demonstrate how the return statement is used to provide values of various data types from methods in Java. Depending on the method's return type, you can use return to send back arrays, strings, booleans, characters, numbers, objects, or any other valid data type in Java. In summary, the return statement in Java is a powerful control statement used within methods to terminate the method's execution and, if applicable, return a value to the calling code. Its flexibility allows you to manage method behavior, return computed values, and handle exceptional cases effectively.

  📌TAGS

★break ★jump ★break statement ★control statement ★control in java ★break in java ★return ★return example

Tutorials